package org.fireflow2.designer.eclipse.commands.datafield;

import java.util.List;

import org.eclipse.gef.commands.Command;
import org.fireflow.model.data.Property;
import org.fireflow.model.data.impl.PropertyImpl;
import org.fireflow2.designer.eclipse.modelwrapper.SubProcessWrapper;
import org.fireflow2.designer.eclipse.modelwrapper.Wrapper;
import org.fireflow2.designer.eclipse.modelwrapper.basic.DataFieldWrapper;
import org.fireflow2.designer.eclipse.modelwrapper.collection.DataFieldListWrapper;
import org.fireflow2.designer.eclipse.modelwrapper.collection.WorkflowElementListWrapper;

public class CreateDataFieldCommand extends Command {
	DataFieldListWrapper datafieldsWrapper = null;
	Property child = null;
	DataFieldWrapper childWrapper = null;
	SubProcessWrapper parent = null;
	
	public DataFieldListWrapper getParent() {
		return datafieldsWrapper;
	}

	public void setParent(DataFieldListWrapper arg0) {
		this.datafieldsWrapper = arg0;
		WorkflowElementListWrapper wrapper = (WorkflowElementListWrapper)this.datafieldsWrapper.getParent();
		parent = wrapper.getSubProcessWrapper();
	}
	public void execute(){
		String name = findANewDataFieldName(datafieldsWrapper);
		child = new PropertyImpl(parent.getWorkflowModelElement(),name);
		childWrapper = new DataFieldWrapper(child);
		parent.addChild(childWrapper,-1);
	}
	
	private String findANewDataFieldName(DataFieldListWrapper dataFieldsWrapper){
		boolean exist = true;
		int n = 1;
		List<Wrapper> datafields = dataFieldsWrapper.getChildren();
		String name = "DataField"
			+ (datafields.size() + n);		
		while(exist){
			boolean found = false;
			for (int i=0;i<datafields.size();i++){
				Wrapper wfElement = (Wrapper)datafields.get(i);
				if (name.equals(wfElement.getName())){
					n++;
					name = "DataField"
						+ (datafields.size() + n);
					found = true;
					break;
				}
			}
			if (!found){
				exist=false;
			}
		}
		return name;
	}		
	
	public void redo(){
		if (datafieldsWrapper!=null){
			parent.addChild(childWrapper,-1);
		}
	}
	
	public void undo(){
		if (datafieldsWrapper!=null){
			parent.deleteChild(childWrapper);
		}
	}	
}
